

package com.ring.server.network;

import com.ring.server.ServerCoreHandler;
import com.ring.server.protocal.Protocal;
import com.ring.server.utils.ServerToolKits;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.ReadTimeoutException;

/**
 * TODO
 *

 * @since 2023-10-09 19:52
 */
public class MBTCPClientInboundHandler extends SimpleChannelInboundHandler<ByteBuf>
{
    private static Logger logger = LoggerFactory.getLogger(MBTCPClientInboundHandler.class);
    private ServerCoreHandler serverCoreHandler = null;

    public MBTCPClientInboundHandler(ServerCoreHandler serverCoreHandler)
    {
        this.serverCoreHandler = serverCoreHandler;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
        try{
            if(e instanceof ReadTimeoutException){
                logger.info("[IMCORE-tcp]客户端{}的会话已超时失效，很可能是对方非正常通出或网络故障" +
                        "，即将以会话异常的方式执行关闭流程 ...", ServerToolKits.clientInfoToString(ctx.channel()));
            }
            serverCoreHandler.exceptionCaught(ctx.channel(), e);
        }catch (Exception e2){
            logger.warn(e2.getMessage(), e);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Gateway.setSocketType(ctx.channel(), Gateway.SOCKET_TYPE_TCP);
        serverCoreHandler.sessionCreated(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Gateway.removeSocketType(ctx.channel());
        serverCoreHandler.sessionClosed(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bytebuf) throws Exception {
        Protocal pFromClient = ServerToolKits.fromIOBuffer(bytebuf);
        serverCoreHandler.messageReceived(ctx.channel(), pFromClient);
    }
}